<script setup lang="ts">

import {ref} from "vue";
import {PlusOutlined} from "@ant-design/icons-vue";
import UserAddForm from "@/views/sys/user/UserAddForm.vue";
import * as userApi from '@/api/userApi'
import * as commonDict from '@/utils/commonDict'
import {message} from "ant-design-vue";

const columns = [
  {
    title: '头像',
    dataIndex: 'avatar',
    width: 100,
    align: 'center'

  },
  {
    title: '账户名',
    dataIndex: 'account',
    width: 150
  },
  {
    title: '用户名',
    dataIndex: 'username',
    width: 150
  },
  {
    title: '角色',
    dataIndex: 'roles',
    width: 150
  },
  {
    title: '性别',
    dataIndex: 'gender',
    width: 80
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    width: 150

  },
  {
    title: '手机号',
    dataIndex: 'phone',
    width: 170
  },
  {
    title: '操作',
    dataIndex: 'action',
  },

]

const tableData = ref([])
const loading = ref(false)
const userAddFormRef = ref(null)

const loadTableData = () => {
  userApi.fetchAllUsers({}).then(res => {
    tableData.value = res
  })
}
loadTableData()

function handleDelete(userId) {
  userApi.deleteAccount({
    userId: userId
  }).then(() => {
    message.success('删除成功')
    loadTableData()
  })
}

</script>

<template>
  <a-card :bordered="false" class="mt-2">
    <a-table bordered :columns="columns" :data-source="tableData" :loading="loading">

      <template #title>
        <div class="flex justify-between">
          <a-space>
            <a-button @click="() => userAddFormRef.onOpen()"   type="primary">
              <template #prefix>
                <PlusOutlined/>
              </template>
              新增
            </a-button>
          </a-space>
        </div>
      </template>

      <template #bodyCell="{ text, record, column }">

        <template v-if="column.dataIndex === 'avatar'">
          <img class="rounded-full" width="50" :src="text" alt="">
        </template>

        <template v-if="column.dataIndex === 'gender'">
          {{commonDict.genderType[text]}}
        </template>

        <template v-if="column.dataIndex === 'roles'">
          <a-tag v-for="item in record.roleName" >{{item}}</a-tag>
        </template>

        <template v-if="column.dataIndex === 'action'">
          <a-space>
            <a-button @click="userAddFormRef.onOpen(record.userId)" type="link">编辑</a-button>
            <a-popconfirm
                title="是否确认删除?"
                ok-text="删除"
                cancel-text="取消"
                @confirm="handleDelete(record.userId)"
            >
              <a-button  type="link"    danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>





    </a-table>

  </a-card>

  <user-add-form  @save-successful="loadTableData" ref="userAddFormRef"></user-add-form>
</template>

<style scoped>

</style>
